<?php
class PostCategoryService{

	public  $dbutil;
	function __construct($dbutil){
		$this->dbutil =  $dbutil;
	}

	/**
	 *
	 * 记录数
	 */
	public function countChildNode($treeNode) {
		$sql = "select count(1) countnum from post_category where parent = " .$treeNode;
		$resutrnarry = $this->dbutil->get_results ( $sql );
		return $resutrnarry [0]->countnum;
	}
	/**
	 *
	 * 获取所有分类的名称
	 */
	public function getCategoryName($condition) {
		if(empty($condition)){
			$sql = "select category_id, category_name from post_category";
		}else{
			$sql = "select category_id, category_name from post_category WHERE ".$condition ." order by c_index";
		}
		return $this->dbutil->get_results($sql);
	}
	
	public function addPostCategory($data) {
		return $this->dbutil->insert("post_category", $data);
	}
	public function updatePostCategory($data, $where) {
		return $this->dbutil->update("post_category", $data, $where);
	}

	public function removePostCategory($id) {
		$isChildsql = " delete from POST_CATEGORY where parent=$id";//删除子节点
		$this->dbutil->query($isChildsql);
		$sql = " delete from POST_CATEGORY where category_id=$id";//删除自身节点
		return $this->dbutil->query($sql);
	}
	
	public function getCategoryRealation(){
		$sql = "select s.category_id ,s.parent from post_category p RIGHT  JOIN post_category s on s.parent = p.category_id ";
		
		$res = $this->dbutil->get_results($sql);
		
		$result = array();
		foreach($res as $re){
			$result[$re->category_id] = $re->parent;
		}
		return $result;
	}
	
	public function mkCatDir(){
		
		$relation = $this->getCategoryRealation();
		
		foreach ($relation as $catId=>$pCatId){
			$catPath = PROJECT;
			
			if($pCatId != null && $pCatId != ""){
				$catPath = $catPath."/".$pCatId;
			}
			if(!file_exists($catPath)){
				mkdir($catPath);
			}
				
			if($catId != null && $catId != ""){
				$catPath = $catPath."/".$catId;
			}
			if(!file_exists($catPath)){
				mkdir($catPath);
			}
		}
	}
	
}